package com.xjnt.frameworks.plugin.quartz;

import static org.quartz.CronScheduleBuilder.cronSchedule;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;

import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;

import com.google.common.collect.Maps;

public class QuartzKit {

	private static SchedulerFactory factory = new StdSchedulerFactory();

	private static Map<String, QJobStore> mapJobs = Maps.newHashMap();
	
	public static void addQJobStore(String jobName, QJobStore jobStore){
		mapJobs.put(jobName, jobStore);
	}
	
	public static QJobStore getQJobStore(String jobName){
		return mapJobs.get(jobName);
	}
	
	public static Map<String, QJobStore> getAllJobs(){
		return mapJobs;
	}
	
	public static void start(){
		try {
			Scheduler scheduler = factory.getScheduler();
			Set<Entry<String, QJobStore>> entries =  mapJobs.entrySet();
			for (Entry<String, QJobStore> entry : entries) {
				QJobStore jobStore = entry.getValue();
				JobDetail jobDetail = newJob(jobStore.getJobClass()).withIdentity(jobStore.getJobName(), jobStore.getJobGroupName()).build();// 任务名，任务组，任务执行类
				// 触发器
				CronTrigger trigger = newTrigger()
						.withIdentity(jobStore.getTriggerName(), jobStore.getTriggerGroupName())// 触发器名,触发器组
						.withSchedule(cronSchedule(jobStore.getCronExpression()))
						.build();
				scheduler.scheduleJob(jobDetail, trigger);
			}
			scheduler.start();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	public static void shutdownAll(){
		try {
			Scheduler scheduler = factory.getScheduler();
			if(scheduler.isStarted()){
				scheduler.shutdown();
			}
			mapJobs.clear();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}
